// pages/login1/login1.js
const app = getApp()
const ipconfig = app.globalData.ipconfig;
var utils = require('../../utils/util')
var http = require('../../utils/http')
Page({


    data: {

    },

    onLoad(options) {

    },

    login() {
		let that = this;
        // 登录
		wx.login({
			success(res1) {
				if (res1.code) {
                    //发起网络请求
                    wx.request({
                      url: 'http://'+ ipconfig + ":8080/mini/login",
                      method:"GET",
                      data:{code:res1.code},
                      success(res){
                        const {flag,data,message} = res.data;
                        
                        const msg = message.split("::")
                        if (!flag) {
                            wx.showToast({
                                title: msg[0],
                                icon: 'fail',
                                duration: 2000
                            })
                        }
                        if(res.statusCode == 400){
                            that.register(msg[1],that)
                        }else{
                            //将登录信息存到本地
                            wx.setStorageSync('token', `${data.tokenHead} ${data.token}`);
                            wx.setStorageSync('userInfo', data.userInfo);
                            wx.setStorageSync('openId', data.openid)
                            that.setData({
                                'loginbtn':utils.hasToken()
                            })
                            //判断是否需要完善信息
                            if (data.userInfo.password == null) {
                                wx.navigateTo({
                                    url: '/pages/login/login',
                                })
                            }
                            wx.navigateTo({
                                url: '/pages/index/index',
                            })
                        }
                        wx.navigateBack()
                      },
                      fail(err){
                        console.log('请求失败',err)
                      }
                    })
					
				} else {
					console.log('登录失败！' + res.errMsg)
				}
            },
            fail:function(res){
                console.log("请求失败",res);
            }
		});
    },


    register(openId,that){
        wx.request({
            url: 'http://' + ipconfig + ':8080/mini/register',
            method: 'GET',
            data: {openId:openId},
            success: function (res) {
                that.login()
            },
            fail: function (err) {
                console.log("请求失败",err);
            }
        })
        
    },
})